const http = require("http");
const fs = require("fs");
const { promisify } = require("util");
const readFiles = promisify(fs.readFile);

http
  .createServer((request, response) => {
    // console.log('我艹了s')
    // console.dir(getPrototypeChain(request))
    // response.end('hello world')

    const { url, method, headers } = request;
    console.log("url---", url);
    if (url === "/" && method === "GET") {
      process.nextTick(async () => {
        try {
          const data = await readFiles("./index.html");
          response.statusCode = 200;
          response.setHeader("Content-Type", "text/html");
          response.end(data);
        } catch (err) {
          console.log(err);
          response.writeHead(500, {
            "Content-Type": "text/plan;charset=utf-8",
          });
          response.end("500 错了");
          return;
        }
      });
      // fs.readFile('index.html',(err,data) => {
      //   if(err) {
      //     response.writeHead(500,{'Content-Type':'text/plan;charset=utf-8'})
      //     response.end('500 错了')
      //     return
      //   }
      //   response.statusCode = 200
      //   response.setHeader('Content-Type','text/html')
      //   response.end(data)
      // })
    } else if (url === "/users" && method === "GET") {
      // process.nextTick(async () => {
      //   try {
      //     const data = await readFiles("./index.html");
      //     response.statusCode = 200;
      //     response.setHeader("Content-Type", "text/html");
      //     response.end(data);
      //   } catch(err) {
      //     console.log(err)
      response.writeHead(500, {
        "Content-Type": "application/json",
      });
      response.end(JSON.stringify([{ name: "toms" }]));
      //   return;
      // }
      // })
    } else if (method === "GET" && headers.accept.indexOf("image/*") !== -1) {
      //流来处理图片
      fs.createReadStream('.'+url).pipe(response)
    }
  })
  .listen(3000);

// 打印原型链
function getPrototypeChain(obj) {
  const protoChain = [];
  while ((obj = Object.getPrototypeOf(obj))) {
    protoChain.push(obj);
  }
  return protoChain;
}
